<template>
  <div class="profile-page">
    <Header :scroll="scroll" />

    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">个人资料</h1>
        <p class="page-subtitle">管理您的个人信息</p>
      </div>
    </div>

    <!-- 用户资料内容区域 -->
    <div class="profile-content">
      <div class="container">
        <div class="profile-layout">
          <!-- 左侧头像区域 -->
          <div class="avatar-section">
            <div class="avatar-container">
              <div class="avatar-wrapper">
                <img v-if="avatarDisplay" :src="proxy.$buildUrl(avatarDisplay)" alt="头像" class="avatar-image" />
                <div v-else class="avatar-placeholder">
                  <span class="avatar-text">{{ displayName.charAt(0) }}</span>
                </div>
              </div>
              <el-upload
                :action="uploadUrl"
                :before-upload="beforeUpload"
                :on-success="uploadSuccess"
                :auto-upload="true"
                accept=".jpg,.jpeg,.png"
                :headers="uploadHeaders"
                :loading="uploadloading"
                :show-file-list="false">
                <button class="change-avatar-btn">
                  <span class="camera-icon">📷</span>
                  更换头像
                </button>
              </el-upload>
            </div>
            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-number">{{ balance }}</span>
                <span class="stat-label">余额</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ points }}</span>
                <span class="stat-label">积分</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ couponCount }}</span>
                <span class="stat-label">优惠券</span>
              </div>
            </div>
          </div>

          <!-- 右侧信息表单 -->
          <div class="info-section">
            <el-form ref="profileFormRef" :model="userInfo" :rules="profileRules" label-width="100px" class="profile-form">
              <div class="form-section">
                <h3 class="section-title">基本信息</h3>
                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="userInfo.nickname" placeholder="请输入昵称" />
                </el-form-item>
                <el-form-item label="真实姓名" prop="realname">
                  <el-input v-model="userInfo.realname" placeholder="请输入真实姓名" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                  <el-radio-group v-model="userInfo.gender">
                    <el-radio :value="1">男</el-radio>
                    <el-radio :value="2">女</el-radio>
                    <el-radio :value="0">保密</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="生日" prop="birthday">
                  <el-date-picker v-model="userInfo.birthday" type="date" value-format="YYYY-MM-DD" placeholder="请选择生日" style="width: 100%" />
                </el-form-item>
              </div>

              <div class="form-section" style="border-bottom: none; padding-bottom: 0">
                <h3 class="section-title">联系信息</h3>
                <el-form-item label="手机号" prop="mobile">
                  <el-input v-model="userInfo.mobile_hidden" placeholder="请输入手机号" disabled />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="userInfo.email" placeholder="请输入邮箱地址" />
                </el-form-item>
                <!-- <el-form-item label="所在地区" prop="region">
                  <el-cascader v-model="userInfo.region" :options="regionOptions" placeholder="请选择所在地区" style="width: 100%" />
                </el-form-item> -->
              </div>

              <!-- <div class="form-section">
                <h3 class="section-title">个人偏好</h3>
                <el-form-item label="茶叶偏好" prop="teaPreference">
                  <el-checkbox-group v-model="userInfo.teaPreference">
                    <el-checkbox value="六堡茶">六堡茶</el-checkbox>
                    <el-checkbox value="普洱茶">普洱茶</el-checkbox>
                    <el-checkbox value="绿茶">绿茶</el-checkbox>
                    <el-checkbox value="红茶">红茶</el-checkbox>
                    <el-checkbox value="乌龙茶">乌龙茶</el-checkbox>
                    <el-checkbox value="白茶">白茶</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="个人简介" prop="bio">
                  <el-input v-model="userInfo.bio" type="textarea" :rows="4" placeholder="介绍一下自己吧..." maxlength="200" show-word-limit />
                </el-form-item>
              </div> -->

              <div class="form-actions">
                <el-button @click="resetForm">重置</el-button>
                <el-button type="primary" @click="saveProfile">保存修改</el-button>
              </div>
            </el-form>
          </div>
        </div>

        <!-- 账号安全区域 -->
        <div class="security-section">
          <h3 class="section-title">账号安全</h3>
          <div class="security-items">
            <div class="security-item">
              <div class="security-info">
                <span class="security-label">登录密码</span>
                <span class="security-desc">定期更换密码，保护账号安全</span>
              </div>
              <button class="security-btn" @click="changePassword">修改密码</button>
            </div>
            <div class="security-item">
              <div class="security-info">
                <span class="security-label">支付密码</span>
                <span class="security-desc">{{
                  userInfo.has_password_secure === '已设置' ? '已设置支付密码，保护您的资金安全' : '未设置支付密码，建议设置以保护资金安全'
                }}</span>
              </div>
              <button class="security-btn" @click="setPaymentPassword">
                {{ userInfo.has_password_secure === '已设置' ? '修改' : '设置' }}支付密码
              </button>
            </div>
            <div class="security-item">
              <div class="security-info">
                <span class="security-label">手机绑定</span>
                <span class="security-desc">{{ userInfo.mobile ? `已绑定：${userInfo.mobile_hidden}` : '未绑定手机号' }}</span>
              </div>
              <button class="security-btn" @click="bindPhone">{{ userInfo.mobile ? '更换' : '绑定' }}手机</button>
            </div>
            <!-- <div class="security-item">
              <div class="security-info">
                <span class="security-label">邮箱绑定</span>
                <span class="security-desc">{{ userInfo.email ? `已绑定：${userInfo.email}` : '未绑定邮箱' }}</span>
              </div>
              <button class="security-btn" @click="bindEmail">{{ userInfo.email ? '更换' : '绑定' }}邮箱</button>
            </div> -->
          </div>
        </div>
      </div>
    </div>

    <!-- 页脚 -->
    <Footer />
  </div>
</template>

<script setup>
  import { getCurrentInstance, ref, reactive, onMounted, computed } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import Header from '@/components/Header.vue'
  import Footer from '@/components/Footer.vue'
  import { useUserStore } from '@/stores/user.js'
  import apiUser from '@/api/modules/user'

  const router = useRouter()
  const route = useRoute()
  const userStore = useUserStore()
  const { proxy } = getCurrentInstance()
  const scroll = ref(false)
  const profileFormRef = ref()

  const userInfo = computed(() => userStore.userInfo)
  const displayName = computed(() => userStore.displayName)
  const avatarDisplay = computed(() => userStore.avatarDisplay)
  const balance = ref(0)
  const points = ref(0)
  const couponCount = ref(0)

  // 初始化
  onMounted(() => {
    loadUserExtInfo()
  })

  const loadUserExtInfo = () => {
    apiUser.GetUserExtInfo().then((res) => {
      balance.value = res.data.balance.toFixed(2)
      points.value = res.data.points
      couponCount.value = res.data.couponCount
    })
  }

  // 监听滚动
  window.addEventListener('scroll', () => {
    scroll.value = window.scrollY > 0
  })

  // 表单验证规则
  const profileRules = {
    nickname: [
      { required: true, message: '请输入昵称', trigger: 'blur' },
      { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' },
    ],
    realname: [{ min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }],
  }

  // 保存资料
  const saveProfile = async () => {
    try {
      await profileFormRef.value.validate()
      // 这里可以添加API调用保存用户信息
      const saveData = {
        info: {
          nickname: userInfo.value.nickname,
          realname: userInfo.value.realname,
          gender: userInfo.value.gender,
          birthday: userInfo.value.birthday,
          email: userInfo.value.email,
        },
      }
      apiUser.updateUserBaseInfo(saveData).then((res) => {
        ElMessage.success('个人资料保存成功')
        userStore.updateUserInfo(userInfo.value)
      })
    } catch (error) {
      console.log('表单验证失败:', error)
    }
  }

  // 重置表单
  const resetForm = () => {
    profileFormRef.value.resetFields()
  }

  // 修改密码
  const changePassword = () => {
    window.scrollTo(0, 0)
    router.push('/change-password')
  }

  // 设置支付密码
  const setPaymentPassword = () => {
    window.scrollTo(0, 0)
    router.push('/payment-password')
  }

  // 绑定/更换手机
  const bindPhone = () => {
    window.scrollTo(0, 0)
    if (userInfo.value.mobile && userInfo.value.mobile !== '') {
      // 已绑定手机号，跳转到换绑页面
      router.push('/change-phone')
    } else {
      // 未绑定手机号，跳转到绑定页面
      router.push('/bind-phone')
    }
  }

  // 绑定邮箱
  const bindEmail = () => {
    ElMessage.info('邮箱绑定功能开发中...')
  }

  const uploadloading = ref(false)
  const url = '/api/App_Upload/UploadFile?company_id=' + userStore.companyId
  const uploadUrl = proxy.$getBaseURL() + url
  const param_json = ref({})
  const uploadHeaders = { ...proxy.$buildHeaderSign(url, userStore.userInfo, param_json.value) }
  const beforeUpload = (rawFile) => {
    // 上传文件之前的钩子
    if (!uploadUrl) {
      ElMessage.warning('请设置正确的上传地址')
      return false
    }
    const isJPG = rawFile.type.includes('image/')
    const isLt20M = rawFile.size / 1024 / 1024 < 1
    if (!isJPG) {
      ElMessage.warning('只能上传图片格式')
    }
    if (!isLt20M) {
      ElMessage.warning('上传文件大小不能超过 1MB')
    }
    return isJPG && isLt20M
  }
  const uploadSuccess = (res, uploadFile) => {
    // 文件上传成功时的钩子
    console.log('文件上传成功时的钩子', res, uploadFile)
    uploadloading.value = true
    if (res.code == 100) {
      userInfo.value.avatar_url = res.data.relativeUrl
      userStore.updateUserInfo(userInfo.value)
    } else {
      ElMessage.error(res.msg)
    }
  }
  const handleRemove = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
  }
</script>

<style scoped>
  .profile-page {
    width: 100%;
    min-height: 100vh;
    background-color: #ffffff;
  }

  /* 页面标题区域 */
  .page-header {
    background: linear-gradient(135deg, #52a58a 0%, #459a7e 100%);
    padding: 60px 0;
    color: white;
    text-align: center;
  }

  .page-title {
    font-size: 32px;
    font-weight: 600;
    margin: 0 0 15px 0;
  }

  .page-subtitle {
    font-size: 16px;
    margin: 0;
    opacity: 0.9;
  }

  /* 用户资料内容区域 */
  .profile-content {
    padding: 40px 0;
  }

  .profile-layout {
    display: grid;
    grid-template-columns: 400px 1fr;
    gap: 40px;
    margin-bottom: 40px;
  }

  /* 左侧头像区域 */
  .avatar-section {
    background: white;
    border-radius: 12px;
    padding: 30px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    height: fit-content;
  }

  .avatar-container {
    text-align: center;
    margin-bottom: 30px;
  }

  .avatar-wrapper {
    width: 120px;
    height: 120px;
    margin: 0 auto 20px;
    position: relative;
  }

  .avatar-image {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
    border: 4px solid #52a58a;
  }

  .avatar-placeholder {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background: linear-gradient(135deg, #52a58a 0%, #459a7e 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    border: 4px solid #52a58a;
  }

  .avatar-text {
    font-size: 36px;
    color: white;
    font-weight: bold;
  }

  .change-avatar-btn {
    background: #f8f9fa;
    border: 1px solid #ddd;
    color: #666;
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 5px;
  }

  .change-avatar-btn:hover {
    background: #52a58a;
    color: white;
    border-color: #52a58a;
  }

  .camera-icon {
    font-size: 16px;
  }

  /* 用户统计 */
  .user-stats {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
  }

  .stat-item {
    text-align: center;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
  }

  .stat-number {
    display: block;
    font-size: 20px;
    font-weight: bold;
    color: #52a58a;
    margin-bottom: 5px;
  }

  .stat-label {
    font-size: 12px;
    color: #666;
  }

  /* 右侧信息表单 */
  .info-section {
    background: white;
    border-radius: 12px;
    padding: 30px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }

  .profile-form {
    max-width: none;
  }

  .form-section {
    margin-bottom: 40px;
    padding-bottom: 30px;
    border-bottom: 1px solid #eee;
  }

  .form-section:last-of-type {
    border-bottom: none;
    margin-bottom: 30px;
  }

  .section-title {
    font-size: 18px;
    color: #333;
    margin: 0 0 25px 0;
    font-weight: 600;
    position: relative;
    padding-left: 15px;
  }

  .section-title::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 18px;
    background: #52a58a;
    border-radius: 2px;
  }

  /* 表单操作按钮 */
  .form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    padding-top: 20px;
    border-top: 1px solid #eee;
  }

  /* 账号安全区域 */
  .security-section {
    background: white;
    border-radius: 12px;
    padding: 30px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }

  .security-items {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .security-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
  }

  .security-info {
    flex: 1;
  }

  .security-label {
    display: block;
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 5px;
  }

  .security-desc {
    font-size: 14px;
    color: #666;
  }

  .security-btn {
    background: #52a58a;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .security-btn:hover {
    background: #459a7e;
    transform: translateY(-1px);
  }

  /* Element Plus 组件样式覆盖 */
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #333;
  }

  :deep(.el-input__inner) {
    border-radius: 8px;
  }

  :deep(.el-textarea__inner) {
    border-radius: 8px;
  }

  :deep(.el-button--primary) {
    background: #52a58a;
    border-color: #52a58a;
  }

  :deep(.el-button--primary:hover) {
    background: #459a7e;
    border-color: #459a7e;
  }

  :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
    background-color: #52a58a;
    border-color: #52a58a;
  }

  :deep(.el-radio__input.is-checked .el-radio__inner) {
    background-color: #52a58a;
    border-color: #52a58a;
  }

  :deep(.el-date-editor.el-input) {
    width: 100%;
  }

  :deep(.el-cascader) {
    width: 100%;
  }

  /* 响应式设计 */
  @media (max-width: 1024px) {
    .profile-layout {
      grid-template-columns: 280px 1fr;
      gap: 30px;
    }

    .avatar-section {
      padding: 25px;
    }

    .info-section {
      padding: 25px;
    }

    .security-section {
      padding: 25px;
    }
  }

  @media (max-width: 768px) {
    .page-header {
      padding: 40px 0;
    }

    .page-title {
      font-size: 24px;
    }

    .page-subtitle {
      font-size: 14px;
    }

    .profile-content {
      padding: 30px 0;
    }

    .profile-layout {
      grid-template-columns: 1fr;
      gap: 20px;
      padding: 0 20px;
    }

    .avatar-section {
      padding: 20px;
    }

    .avatar-wrapper {
      width: 100px;
      height: 100px;
    }

    .avatar-text {
      font-size: 30px;
    }

    .user-stats {
      grid-template-columns: repeat(3, 1fr);
      gap: 10px;
    }

    .stat-item {
      padding: 12px;
    }

    .stat-number {
      font-size: 18px;
    }

    .stat-label {
      font-size: 11px;
    }

    .info-section {
      padding: 20px;
    }

    .form-section {
      margin-bottom: 30px;
      padding-bottom: 20px;
    }

    .section-title {
      font-size: 16px;
      margin-bottom: 20px;
    }

    .form-actions {
      flex-direction: column;
      gap: 10px;
    }

    .form-actions .el-button {
      width: 100%;
    }

    .security-section {
      padding: 20px;
      margin: 0 20px;
    }

    .security-item {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;
      padding: 15px;
    }

    .security-btn {
      align-self: stretch;
      text-align: center;
      padding: 10px;
    }

    /* Element Plus 移动端适配 */
    :deep(.el-form-item) {
      margin-bottom: 20px;
    }

    :deep(.el-form-item__label) {
      font-size: 14px;
      line-height: 1.4;
    }

    :deep(.el-input__inner) {
      font-size: 14px;
    }

    :deep(.el-textarea__inner) {
      font-size: 14px;
    }

    :deep(.el-radio) {
      margin-right: 15px;
      margin-bottom: 10px;
    }

    :deep(.el-radio__label) {
      font-size: 14px;
    }

    :deep(.el-checkbox) {
      margin-right: 15px;
      margin-bottom: 10px;
    }

    :deep(.el-checkbox__label) {
      font-size: 14px;
    }
  }

  @media (max-width: 480px) {
    .page-header {
      padding: 30px 0;
    }

    .page-title {
      font-size: 20px;
    }

    .page-subtitle {
      font-size: 13px;
    }

    .profile-content {
      padding: 20px 0;
    }

    .profile-layout {
      padding: 0 15px;
      gap: 15px;
    }

    .avatar-section {
      padding: 15px;
    }

    .avatar-wrapper {
      width: 80px;
      height: 80px;
      margin-bottom: 15px;
    }

    .avatar-text {
      font-size: 24px;
    }

    .change-avatar-btn {
      padding: 6px 12px;
      font-size: 13px;
    }

    .user-stats {
      gap: 8px;
    }

    .stat-item {
      padding: 10px;
    }

    .stat-number {
      font-size: 16px;
    }

    .stat-label {
      font-size: 10px;
    }

    .info-section {
      padding: 15px;
    }

    .form-section {
      margin-bottom: 25px;
      padding-bottom: 15px;
    }

    .section-title {
      font-size: 15px;
      margin-bottom: 15px;
      padding-left: 12px;
    }

    .section-title::before {
      width: 3px;
      height: 15px;
    }

    .security-section {
      padding: 15px;
      margin: 0 15px;
    }

    .security-item {
      padding: 12px;
    }

    .security-label {
      font-size: 15px;
    }

    .security-desc {
      font-size: 13px;
    }

    .security-btn {
      padding: 8px 12px;
      font-size: 13px;
    }

    /* Element Plus 超小屏适配 */
    :deep(.el-form-item) {
      margin-bottom: 18px;
    }

    :deep(.el-form-item__label) {
      font-size: 13px;
      line-height: 1.3;
    }

    :deep(.el-input__inner) {
      font-size: 13px;
      padding: 8px 12px;
    }

    :deep(.el-textarea__inner) {
      font-size: 13px;
      padding: 8px 12px;
    }

    :deep(.el-radio) {
      margin-right: 12px;
      margin-bottom: 8px;
    }

    :deep(.el-radio__label) {
      font-size: 13px;
    }

    :deep(.el-checkbox) {
      margin-right: 12px;
      margin-bottom: 8px;
    }

    :deep(.el-checkbox__label) {
      font-size: 13px;
    }

    :deep(.el-button) {
      padding: 8px 15px;
      font-size: 13px;
    }

    :deep(.el-date-editor .el-input__inner) {
      padding: 8px 12px;
    }
  }
</style>
